package com.example.emergencyattempt01.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import androidx.annotation.NonNull;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import com.example.emergencyattempt01.user.User;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import android.os.Handler;
import org.json.JSONException;
import org.json.JSONObject;

public class St_BookAdapter extends BaseAdapter {
    Context context;
    List<Map<String,Object>> itemList;
    ViewHolder viewHolder=null;
    User student;



    public St_BookAdapter(Context context, List<Map<String, Object>> itemList,User student) {
        this.context = context;
        this.itemList = itemList;
        this.student=student;
    }

    class ViewHolder
    {
        TextView ISBNField;
        TextView bookNameField;
        TextView authorField;
        TextView pressField;
        TextView sumNumberField;
        TextView nowNumberField;
        TextView typeField;
        TextView introductionField;

        Button borrowRequest;
    }

    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
         switch (msg.what)
         {
             case SEND_SUCCESS:
                 int position=(int)msg.obj;
                 Toast.makeText(context,"已发送请求,正在等待管理员审核",Toast.LENGTH_SHORT).show();
                 itemList.remove(position);
                 notifyDataSetChanged();// 防止误操作，借完直接没了，下次还借时，刷新一下就好了
                 break;
             case SEND_FAIL:
                 Toast.makeText(context,"发送失败，请检查网络",Toast.LENGTH_SHORT).show();
                 break;
             case REQUEST_DENY:
                 Toast.makeText(context,"最多只能借5本哦",Toast.LENGTH_SHORT).show();
                 break;

         }
        }
    };
    final int SEND_SUCCESS=0x001;
    final int SEND_FAIL=0x002;
    final int REQUEST_DENY=0x004;

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }
    public String getISBN(int position)
    {
        return (String)itemList.get(position).get("ISBN");
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        if(convertView==null)
        {
            viewHolder=new ViewHolder();
            convertView=inflater.inflate(R.layout.st_book_item,null);
            viewHolder.authorField=convertView.findViewById(R.id.st_book_author);
            viewHolder.bookNameField=convertView.findViewById(R.id.st_book_name);
            viewHolder.introductionField=convertView.findViewById(R.id.st_book_introduction);
            viewHolder.ISBNField=convertView.findViewById(R.id.st_book_ISBN);
            viewHolder.nowNumberField=convertView.findViewById(R.id.st_book_nowNumber);
            viewHolder.sumNumberField=convertView.findViewById(R.id.st_book_sumNumber);
            viewHolder.pressField=convertView.findViewById(R.id.st_book_press);
            viewHolder.typeField=convertView.findViewById(R.id.st_book_type);
            viewHolder.borrowRequest=convertView.findViewById(R.id.st_borrow_book);

            convertView.setTag(viewHolder);
        }
        else
        {
         viewHolder=(ViewHolder) convertView.getTag();
        }
        /** 设置每个item的值
         * 注意，自外传入数值时，应当做一层筛选
         * 把所有在库数目等于零的都筛掉
         */
        String ISBN;
        String bookName;
        String author;
        String press;
        long sumNumber;
        long nowNumber;
        String type;
        String introduction;
        long uid;

        ISBN=(String)itemList.get(position).get("ISBN");
        bookName=(String)itemList.get(position).get("bookName");
        author=(String)itemList.get(position).get("author");
        press=(String)itemList.get(position).get("press");
        introduction=(String)itemList.get(position).get("introduction");
        type=(String)itemList.get(position).get("type");
        sumNumber=(long)itemList.get(position).get("sumNumber");
        nowNumber=(long)itemList.get(position).get("nowNumber");
        uid=student.getUid();

        viewHolder.ISBNField.setText(ISBN);
        viewHolder.bookNameField.setText(bookName);
        viewHolder.typeField.setText(type);
        viewHolder.pressField.setText(press);
        viewHolder.sumNumberField.setText(sumNumber+"册");
        viewHolder.nowNumberField.setText(nowNumber+"册");
        viewHolder.authorField.setText(author);
        viewHolder.introductionField.setText(introduction);
        // 设置监听，发送借书请求
        sendBorrowRequest(position);
        return convertView;
    }

    private void sendBorrowRequest(final int position) {
        viewHolder.borrowRequest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder=new AlertDialog.Builder(context);
                builder.setMessage("确定要借阅这本书吗？");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread()
                        {
                            @Override
                            public void run() {
                                try {
                                    // 在发送请求之前，先向服务器发送一个请求，查询当前用户一共有多少本书了
                                    // 这里借用了一下登录方法的返回个人信息功能
                                    JSONObject jsonObject1=new JSONObject();
                                    jsonObject1.put("uid",student.getUid());
                                    jsonObject1.put("password",student.getPassword());
                                    String toSerer1=String.valueOf(jsonObject1);
                                    ServerMessage serverMessage1=NetWorkUtils.getInstance().create(toSerer1,"/login");
                                    if(serverMessage1.getRespondCode()==200)
                                    {
                                        String fromServer1=(String) serverMessage1.getFromServer();
                                        JSONObject object1=new JSONObject(fromServer1);
                                        int borrowNumber=object1.getInt("ownBooks");
                                        if(borrowNumber>5)
                                        {
                                            // 表明已经提交了5份申请了，不能再提交了
                                            Message message=new Message();
                                            message.what=REQUEST_DENY;
                                            handler.sendMessage(message);
                                        }
                                        else {
                                            // 可以正常提交了
                                            // 打包uid，ISBN，borrowTime发给服务器
                                            JSONObject object=new JSONObject();
                                            object.put("uid",student.getUid());
                                            object.put("ISBN",(String)itemList.get(position).get("ISBN"));
                                            object.put("borrowTime",System.currentTimeMillis());
                                            String toServer=String.valueOf(object);

                                            ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/borrow_book_request");
                                            int code=serverMessage.getRespondCode();
                                            if(code==200)
                                            {
                                                String fromServer=(String) serverMessage.getFromServer();
                                                JSONObject objectBack=new JSONObject(fromServer);
                                                boolean can=objectBack.getBoolean("can");
                                                if(can) // 表示能借
                                                {
                                                    Message message=new Message();
                                                    message.obj=position;
                                                    message.what=SEND_SUCCESS;
                                                    handler.sendMessage(message);
                                                }
                                                else // 表示已经借满5本了，不能再借了
                                                {
                                                    Message message=new Message();
                                                    message.what=REQUEST_DENY;
                                                    handler.sendMessage(message);
                                                }
                                            }
                                            else // 网络问题
                                            {
                                                Message message=new Message();
                                                message.what=SEND_FAIL;
                                                handler.sendMessage(message);
                                            }
                                        }
                                    }
                                    else {
                                        Message message=new Message();
                                        message.what=SEND_FAIL;
                                        handler.sendMessage(message);
                                    }
                                }catch (JSONException e){e.printStackTrace();}
                                catch (IOException e){e.printStackTrace();
                                    Message message=new Message();
                                    message.what=SEND_FAIL;
                                    handler.sendMessage(message);}
                            }
                        }.start();
                    }
                });
                builder.create().show();
            }
        });

    }
}
